import multiprocessing
import os, subprocess, sys
from posixpath import join
from os import path
import time
from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler

import paramiko

class myHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2', '/RPC3')


if __name__ == '__main__':
    src = sys.argv[1]
    trg = sys.argv[2]
    vecname = sys.argv[3]
    seeds = range(0, 1)
    # seeds = [0]
    exp_name = 'Apr16_normword2vec'
    exp_id = src + '-' + trg + '_' + vecname
    exp_path = path.join('dumped', exp_name, exp_id)
    if not path.exists(exp_path):
        os.makedirs(exp_path)
    log_file_path = path.join(exp_path , "vecmap_log.txt")
    file_mode = 'a' if os.path.exists(log_file_path) else 'w'

    def fake_process(msg):
        for i in range(10):
            print(i, end='\r')
            time.sleep(1)
        return
    def induction_process(msg):
        for i in seeds:
            subprocess.run([
                "python3", "vecmap_main_modularized.py", 
                # "dumped/Seg04_lowcutoff/vi-en/vectors-vi.txt", "dumped/Sep06_stepcutoff/vi-en/vectors-en.txt",
                f"dumped/word2normvec/{vecname}.{src}.vec",
                f"dumped/word2normvec/{vecname}.{trg}.vec", 
                path.join(exp_path, src + ".mapped_emb.txt"), path.join(exp_path, trg + ".mapped_emb.txt"),
                "--unsupervised",
                "--verbose",
                "--validation", "data/crosslingual/dictionaries/" + src + '-' + trg + ".0-5000.txt",
                # "--batch_size", "4000",
                # "--vocabulary_cutoff", "20000",
                "--log", log_file_path,
                "--seed", str(i),
                "--cuda",
                "--normalize", "none",
            ])
            with open(log_file_path, file_mode) as logfile:
                subprocess.run([
                    "python3","eval_translation.py",
                    path.join(exp_path, src + ".mapped_emb.txt"),
                    path.join(exp_path, trg + ".mapped_emb.txt"),
                    "-d", "data/crosslingual/dictionaries/" + src + '-' + trg + ".0-5000.txt",
                    "--cuda",
                    "--seed", str(i),
                    "--retrieval", "csls",
                ], stdout=logfile)
                if msg:
                    print(msg, file=logfile)



    with SimpleXMLRPCServer(('', 19810), requestHandler=myHandler, allow_none=True) as server:
        server.register_introspection_functions()
        
        train_process = None
        @server.register_function(name='induction')
        def vecmap_induction(msg = ''):
            if not hasattr(vecmap_induction, 'train_process'):
                vecmap_induction.train_process = None
            if vecmap_induction.train_process:
                print('Waiting for last training processing...')
                vecmap_induction.train_process.join()
                print('Last processing is done.')
    
            print(f'Copying new trained {msg} vectors.')
            sshcli = paramiko.SSHClient()
            sshcli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            sshcli.connect(hostname='10.10.255.118', port=22, username='changfu', password='open118')
            sftp = sshcli.open_sftp()
            sftp.get(
                f"/home/changfu/dumped/word2normvec/{vecname}.{src}.vec",
                f"/home/hlcao/.changfu/dumped/word2normvec/{vecname}.{src}.vec"
            )
            sftp.get(
                f"/home/changfu/dumped/word2normvec/{vecname}.{trg}.vec",
                f"/home/hlcao/.changfu/dumped/word2normvec/{vecname}.{trg}.vec"
            )
            sftp.close()
            sshcli.close()
            print('Copyed.')
            vecmap_induction.train_process = multiprocessing.Process(target=induction_process, args=(msg,))
            vecmap_induction.train_process.start()
            print('Training starts.')

        
        print('server start.')
        server.serve_forever()

